<template>
  <div class="statistics-cards">
    <el-row :gutter="16">
      <!-- 申请统计卡片 -->
      <el-col :span="12">
        <el-card class="stat-card application-stats">
          <div class="card-header">
            <h3>申请统计</h3>
            <el-button type="text" @click="refreshStats">刷新</el-button>
          </div>
          <div class="stats-content">
            <div class="stat-item">
              <div class="stat-number">{{ stats.totalApplications }}</div>
              <div class="stat-label">总申请数</div>
            </div>
            <div class="stat-item">
              <div class="stat-number pending">{{ stats.pendingApplications }}</div>
              <div class="stat-label">待审批</div>
            </div>
            <div class="stat-item">
              <div class="stat-number approved">{{ stats.approvedApplications }}</div>
              <div class="stat-label">已审批</div>
            </div>
            <div class="stat-item">
              <div class="stat-number allocated">{{ stats.allocatedApplications }}</div>
              <div class="stat-label">已分配</div>
            </div>
          </div>
          <div class="progress-section">
            <div class="progress-item">
              <span>审批率</span>
              <el-progress :percentage="stats.approvalRate" :color="progressColors.approval" />
            </div>
            <div class="progress-item">
              <span>分配率</span>
              <el-progress :percentage="stats.allocationRate" :color="progressColors.allocation" />
            </div>
          </div>
        </el-card>
      </el-col>

      <!-- 处理效率折线图 -->
      <el-col :span="12">
        <el-card class="stat-card efficiency-chart">
          <div class="card-header">
            <h3>处理效率趋势</h3>
            <el-select v-model="chartPeriod" size="small" style="width: 100px">
              <el-option label="7天" value="7" />
              <el-option label="30天" value="30" />
              <el-option label="90天" value="90" />
            </el-select>
          </div>
          <div class="chart-container">
            <div ref="chartRef" class="chart"></div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 详细统计表格 -->
    <el-row :gutter="16" style="margin-top: 16px;">
      <el-col :span="24">
        <el-card class="stat-card detailed-stats">
          <div class="card-header">
            <h3>详细统计</h3>
            <el-date-picker
              v-model="dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              size="small"
              @change="handleDateRangeChange"
            />
          </div>
          <el-table :data="detailedStats" style="width: 100%">
            <el-table-column prop="date" label="日期" width="120" />
            <el-table-column prop="newApplications" label="新申请" width="100" />
            <el-table-column prop="approved" label="已审批" width="100" />
            <el-table-column prop="allocated" label="已分配" width="100" />
            <el-table-column prop="rejected" label="已拒绝" width="100" />
            <el-table-column prop="avgProcessTime" label="平均处理时间" width="120">
              <template #default="{ row }">
                {{ row.avgProcessTime }}小时
              </template>
            </el-table-column>
            <el-table-column prop="satisfaction" label="满意度" width="100">
              <template #default="{ row }">
                <el-rate v-model="row.satisfaction" disabled show-score />
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, watch } from 'vue'
import { ElMessage } from 'element-plus'
import * as echarts from 'echarts'
import { getStatistics, getChartData, getDetailedStats } from '@/api/classroom'
import dayjs from 'dayjs'

// 统计数据
const stats = ref({
  totalApplications: 0,
  pendingApplications: 0,
  approvedApplications: 0,
  allocatedApplications: 0,
  approvalRate: 0,
  allocationRate: 0
})

// 图表相关
const chartRef = ref()
const chartPeriod = ref('7')
let chartInstance: echarts.ECharts | null = null

// 日期范围
const dateRange = ref([])

// 详细统计数据
interface DetailedStatItem {
  date: string
  newApplications: number
  approved: number
  allocated: number
  rejected: number
  avgProcessTime: number
  satisfaction: number
}

const detailedStats = ref<DetailedStatItem[]>([])

// 进度条颜色
const progressColors = {
  approval: '#67C23A',
  allocation: '#409EFF'
}

// 获取统计数据
async function fetchStats() {
  try {
    const res = await getStatistics()
    if (res && res.data) {
      Object.assign(stats.value, res.data)
    }
  } catch (error) {
    ElMessage.error('获取统计数据失败')
  }
}

// 获取图表数据
async function fetchChartData() {
  try {
    const res = await getChartData({ period: Number(chartPeriod.value) })
    return res.data // [{date, applications, processed}]
  } catch (error) {
    ElMessage.error('获取图表数据失败')
    return []
  }
}

// 初始化图表
async function initChart() {
  if (!chartRef.value) return
  chartInstance = echarts.init(chartRef.value)
  const chartData = await fetchChartData()
  const option = {
    tooltip: { trigger: 'axis', axisPointer: { type: 'cross' } },
    legend: { data: ['新申请', '已处理'] },
    grid: { left: '3%', right: '4%', bottom: '3%', containLabel: true },
    xAxis: { type: 'category', data: chartData.map((item: any) => item.date) },
    yAxis: { type: 'value' },
    series: [
      {
        name: '新申请',
        type: 'line',
        smooth: true,
        data: chartData.map((item: any) => item.applications),
        itemStyle: { color: '#409EFF' }
      },
      {
        name: '已处理',
        type: 'line',
        smooth: true,
        data: chartData.map((item: any) => item.processed),
        itemStyle: { color: '#67C23A' }
      }
    ]
  }
  chartInstance.setOption(option)
}

// 获取详细统计数据
async function fetchDetailedStats() {
  try {
    if (!dateRange.value || dateRange.value.length !== 2 || !dateRange.value[0] || !dateRange.value[1]) {
      ElMessage.error('请选择开始和结束日期')
      return
    }
    const [start, end] = dateRange.value
    const startStr = dayjs(start).format('YYYY-MM-DD')
    const endStr = dayjs(end).format('YYYY-MM-DD')
    const res = await getDetailedStats({ start: startStr, end: endStr })
    detailedStats.value = res.data
  } catch (error) {
    ElMessage.error('获取详细统计数据失败')
  }
}

// 刷新统计
function refreshStats() {
  fetchStats()
  fetchDetailedStats()
  initChart()
}

// 日期范围变化
function handleDateRangeChange() {
  fetchDetailedStats()
}

// 监听图表周期变化
watch(chartPeriod, () => {
  initChart()
})

// 监听窗口大小变化
function handleResize() {
  if (chartInstance) {
    chartInstance.resize()
  }
}

onMounted(() => {
  fetchStats()
  fetchDetailedStats()
  initChart()
  
  window.addEventListener('resize', handleResize)
})

// 组件卸载时清理
import { onUnmounted } from 'vue'
onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
  if (chartInstance) {
    chartInstance.dispose()
  }
})
</script>

<style scoped>
.statistics-cards {
  margin-top: 16px;
}

.stat-card {
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(22,93,255,0.04);
  min-height: 200px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.card-header h3 {
  margin: 0;
  color: #303133;
  font-size: 16px;
  font-weight: 600;
}

.stats-content {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 20px;
  margin-bottom: 24px;
}

.stat-item {
  text-align: center;
}

.stat-number {
  font-size: 28px;
  font-weight: bold;
  color: #409EFF;
  margin-bottom: 8px;
}

.stat-number.pending {
  color: #E6A23C;
}

.stat-number.approved {
  color: #67C23A;
}

.stat-number.allocated {
  color: #909399;
}

.stat-label {
  font-size: 14px;
  color: #606266;
}

.progress-section {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.progress-item {
  display: flex;
  align-items: center;
  gap: 12px;
}

.progress-item span {
  font-size: 14px;
  color: #606266;
  min-width: 60px;
}

.chart-container {
  height: 200px;
}

.chart {
  width: 100%;
  height: 100%;
}

.detailed-stats {
  margin-top: 16px;
}
</style> 